<?php

namespace Api\Controller;

class AdController extends BaseController {
    /**
     * 记录用户 看广告 回答问题 分享给好友的接口
     * $action 0:看广告 1:回答问题 2:分享
     * 2018年10月11日更改，此接口不再提供广告答题记录
     */
    public function log(){
        // todo 赚钱记录表 ln_account_log和ln_users表修改.
        $token = I('token');
        $map['token'] = $token;
        $user_id = M('users')->field('user_id')->where($map)->find();
        $data['user_id'] = $user_id['user_id'];
        $data['ad_id'] = I("post.ad_id", 0, 'intval');
        $data['source'] = I("post.source", 0, 'intval');
        $data['create_time'] = time();
        if (empty($data['user_id'])){
            $this->returnInfo('-1','请传入正确的用户ID');
        }
        if (empty($data['ad_id'])){
            $this->returnInfo('-1','请传入正确的广告ID');
        }
        $data['action'] = I("post.action", 0, 'intval');
        switch ($data['action']){
            case 0:
                //看广告
                // $this->returnInfo('-1','系统升级，看广告后不需调此接口');
                $data['is_valid'] = 1;
                $result = M('user_surf_ad_log')->add($data);
                break;
            case 1:
                //回答问题
                $this->returnInfo('-1','系统升级，答题后不需调此接口');
                $result = M('user_answer_ad_log')->add($data);
                break;
            case 2:
                // 分享
                $data['share_url'] = I("share_url");
                if (empty($data['user_id'])){
                    $this->returnInfo('-1','分享的链接不能为空');
                }
                $result = M('user_share_ad_log')->add($data);
                break;
            default:
                $this->returnInfo('-1','请传入正确的类型');
        }
        if ($result){
                $this->returnInfo('1','日志记录成功');
        }else{
                $this->returnInfo('-1','日志记录失败');
        }
    }

    /**
    *广告详情  登录与未登录两种情况
    *@param user_id 
    *@param ad_id
    */
    public function adDeatil(){
        $ad_id = I("post.ad_id", 0, 'intval');
        $ad = M('ad')->field('ad_id,ad_link,ad_code')->where("ad_id=$ad_id")->find();
        if($ad)
        {
            $ad['ad_code'] = parseMediaUrl($ad['ad_code']);
        }
        $this->returnInfo('1','获取详情成功',$ad);
    }   
    /**
     * 用户看广告的接口
     */
    public function income(){
        $data['token'] = I('token');
        $map['token'] = $data['token'];
        $user_id = M('users')->field('user_id,first_leader')->where($map)->find();
        $data['user_id'] = $user_id['user_id'];
        $data['ad_id'] = I("post.ad_id", 0, 'intval');
        $data['source'] = I("post.source", 0, 'intval');
        $data['create_time'] = time();
        $data['first_leader'] = $user_id['first_leader'];
        if (empty($data['user_id'])){
            $this->returnInfo('-1','请传入正确的用户ID');
        }
        if (empty($data['ad_id'])){
            $this->returnInfo('-1','请传入正确的广告ID');
        }
        // 收入 从ln_ad_extent表中查询
        $incomes = D('ad_extent')
            ->field("rebate")->where(["ad_id"=>$data['ad_id'],"is_join_rebate"=>1])
            ->find();
        doLog("[param]".json_encode(I())."\r\n[income]".json_encode($incomes),"ad_log");
        if (empty($incomes)){
            // 不参加赚钱活动
            $this->returnInfo('-1','对应广告不参加赚钱活动');
        }


        #是否观看
        $is_look = M('user_surf_ad_log')->where([
            "user_id" => $user_id,
            "ad_id" => $data['ad_id'],
            "is_valid" => 1,
            "create_time" => ["gt",strtotime( date('Y-m-d')." 00:00:00" )]
        ])->find();

        if(  $is_look )
        {
            doLog("[ad_id]{$data['ad_id']}\r\n[user_id]{$data['user_id']}\r\n[是否观看过]{$is_look}","ad_log");
            $this->returnInfo('-1','今天已经观看过了');
        }

        $logData = [
            "user_id" => $data['user_id'],
            "ad_id" => $data['ad_id'],
            "create_time" => time(),
            "source" => 0,
            "is_valid" => 1,
        ];

        if ($logData['is_valid'] == 1){
            $income = $incomes['rebate'] > 0 ? $incomes['rebate'] : 0;
            if( $income > 0 )
            {
                #给积分
                $add_points = accountLog($data['first_leader'],0,$income,'广告观看');
                #给一级分销 n% 积分
                if( $data['first_leader'] )
                {

                    $conf = M('config')->where([
                        "name" => 'ad'
                    ])->getField('value');

                    $first_leader_income = $income * $conf / 100;
                    
                    if( $first_leader_income > 0 )
                    {
                        $add_points1 = accountLog($data['first_leader'],0,$first_leader_income,"下级观看广告");
                    }
                }
                doLog("[ad_id]{$data['ad_id']}\r\n[user_id]{$data['user_id']}\r\n[first_leader]{$data['first_leader']}\r\n[分发收益]\r\n[user]".json_encode($add_points)."\r\n[leader]".( $add_points1 ? json_encode($add_points1) : "" ), "ad_log" );
            }
        }

        // 添加记录到ln_user_surf_ad_income_log表中
        $result = D('user_surf_ad_log')->add($logData);
        if ($result){
            $this->returnInfo('1','成功');
        }else{
            $this->returnInfo('-1','失败');
        }
    }

    /**
     * 通过广告ID获取问题
     */
    public function getQuestion(){
        $ad_id = I("post.ad_id", 0, 'intval');
        if (empty($ad_id)){
            $this->returnInfo('-1','请传入正确的广告ID');
        }
        // 问题
        $questionArray = D('ad_extent')
            ->field("ad_id,question,answer")
            ->where(["ad_id"=>$ad_id,"is_join_rebate"=>1])
            ->find();
        if (empty($questionArray))
        {
            $this->ajaxReturn(array('status'=>-1,'msg'=>'对应广告未参与看广告答题返现'));
        }
        $questionArray['answer'] = unserialize($questionArray['answer']);
        $questionArray['answer'] = is_array($questionArray['answer']) ? $questionArray['answer'] : [];
        if( isset($questionArray['answer']['selected']) )
        {
            unset($questionArray['answer']['selected']);
        }
        $this->ajaxReturn(array('status'=>1,'msg'=>'获取成功','result'=>$questionArray));
    }

    /**
     * 回答问题的接口
     */
    public function answerQuestion(){
        $token = I('token');
        $map['token'] = $token;
        $user = M('users')->field('user_id,first_leader')->where($map)->find();
        $user_id = $user['user_id'];
        $first_leader = $user['first_leader'];
        $ad_id = I("post.ad_id", 0, 'intval');
        $answer = I("post.answer", '');
        if (empty($ad_id))
        {
            $this->returnInfo('-1','请传入正确的广告ID');
        }

        if ('' === $answer ){
            $this->ajaxReturn(array('status'=>-1,'msg'=>'答案不能为空'));
        }
        // 问题
        $questionArray = D('ad_extent')
            ->field("ad_id,question,answer,rebate")
            ->where(["ad_id"=>$ad_id,"is_join_rebate"=>1])
            ->find();
        if (empty($questionArray)){
            $this->returnInfo('-1','对应广告未参与看广告答题返现');
        }

        #看看今天是否回答过
        $is_answered = M('user_answer_ad_log')->where([
            "user_id" => $user_id,
            "ad_id" => $ad_id,
            "is_valid" => 1,
            "create_time" => ["gt",strtotime( date('Y-m-d')." 00:00:00" )]
        ])->find();

        if(  $is_answered )
        {
            doLog("[user_id]{$user_id}[ad_id]{$ad_id}","answer_invalid_log");
            $this->returnInfo('-1','今天已经回答过了，明天再来吧');
        }

        $questionArray['answer'] = unserialize($questionArray['answer']);

        $logData = [
            "user_id" => $user_id,
            "ad_id" => $ad_id,
            "create_time" => time(),
            "source" => 0,
            "status" => 0,
            "is_valid" => 1,
        ];

        M()->startTrans();

        if (!empty($questionArray['answer']) && isset($questionArray['answer']['selected']) && $answer == $questionArray['answer']['selected'])
        {
            $logData['status'] = 1;
            // 收入 从ln_ad_extent表中查询
            $income = $questionArray['rebate'] > 0 ? $questionArray['rebate'] : 0;

            if( $income > 0 )
            {
                #给积分
                $add_points = accountLog($user_id,0,$income,'广告答题');

                #给一级分销 n% 积分
                if( $first_leader )
                { 
                    $conf = M('config')->where([
                        "name" => 'ad'
                    ])->getField('value');

                    $first_leader_income = $income * $conf / 100;

                    if( $first_leader_income > 0 )
                    {
                        $add_points1 = accountLog($first_leader,0,$first_leader_income,"下级答题");
                    }
                }
            }
        }
        #记录在案
        $log = M('user_answer_ad_log')->add($logData);

        if( !$log )
        {
            M()->rollback();
            $this->returnInfo('-1','系统繁忙');
        }

        M()->commit();

        if( $logData['status'] == 1)
        {
            $this->returnInfo('1','回答正确');
        }
        $this->returnInfo('-1','回答错误');
    }

    //广告点击插入数据库
    public function recordClick(){
        $ad_id=I('id');//广告id
        $user_id=I('userId');//用户id
        $ad_data=M('ad')->where("ad_id=".$ad_id)->find();
        if(!$ad_data){
            $this->returnInfo(0,'没有找到这条广告');
        }
        $res=M('ad')->where("ad_id=".$ad_id)->save(array('click_count'=>$ad_data['click_count']+1));
        if($res){
            $time=date('Y-m-d H:i:s',time());
            $data=['user_id'=>$user_id,'ad_id'=>$ad_id,'create_time'=>$time];
            $click_res=M('ad_click')->add($data);
            if($click_res){
                $this->returnInfo('1','成功');
            }else{
                $this->returnInfo('0','失败');
            }
        }else{
            $this->returnInfo('0','失败');
        }
    }

    public function ad_lists(){
        $url = "http://101.201.70.115/index.php?s=/Api/Lottery/index/index.html";
        $this->returnInfo('1','成功',$url);
    }

    //广告列表
    public function lists(){
        $token = I('token');
        $map['token'] = $token;
        $user_id = M('users')->field('user_id')->where($map)->find();
        $user_id = $user_id['user_id'];
        $now = time();
        // 应付苹果审核
        if($this->platform == 1)
        {
            $this->returnInfo('1','获取成功',[]);
        }
        $adList = M('ad as a')
                ->join('ln_ad_extent as ade on ade.ad_id = a.ad_id')
                ->field('a.ad_id,a.ad_code,a.media_type')
                ->where("ade.is_join_rebate=1 and a.end_time>'$now'")
                ->order('orderby asc,ad_id desc')
                ->select();
        foreach ($adList as $key => &$value) {
            $where['ad_id'] = $value['ad_id'];
            $where['user_id'] = $user_id;
            $where['is_valid'] = 1;
            $answer = M('user_answer_ad_log')->field('user_id')->where($where)->find();
            if ($answer) {
                $value['answer'] = 1;
            }else{
                $value['answer'] = -1;
            }
            $look = M('user_surf_ad_log')->field('user_id')->where($where)->fetchSql(1)->find();
            if ($look) {
                $value['look'] = 1;
            }else{
                $value['look'] = -1;
            }
            $fen = M('user_share_ad_log')->field('user_id')->where(array('ad_id'=>$value['ad_id'],'user_id'=>$user_id))->find();
            if ($fen) {
                $value['fen'] = 1;
            }else{
                $value['fen'] = -1;
            }
            $value['ad_code'] = parseMediaUrl($value['ad_code']);
        }
        $this->returnInfo('1','获取成功',$adList);
    }


    public function explain(){
        $where['key'] = "看广告说明";
        $agreement = M('agreement')->field('value')->where($where)->find();
        $agreement = $agreement?$agreement:[];
        if ($agreement) {
           $this->returnInfo('1','看广告说明获取成功',$agreement);
        }else{
            $this->returnInfo('-1','暂无广告说明',$agreement);
        }
        
    }
}